package com.jilujia.domain.user.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jilujia.domain.user.User;
import com.jilujia.domain.user.UserFollowHotel;
import com.jilujia.domain.user.UserManager;
import com.jilujia.domain.user.repository.UserFollowHotelRepository;
import com.jilujia.domain.user.repository.UserRepository;
import com.jilujia.framework.domain.AbstractService;

/**
 * A JPA-based implementation of the Booking Service. Delegates to a JPA entity
 * manager to issue data access calls against the backing repository. The
 * EntityManager reference is provided by the managing container (Spring)
 * automatically.
 */
@Service("userService")
@Transactional(readOnly = true)
public class UserServiceImpl extends AbstractService implements UserService {

	@Autowired
	private UserRepository userRepository;

	@Autowired
	private UserFollowHotelRepository userFollowRepository;

	public User findEnabledUser(Long id) {
		User user = userRepository.findOne(id);
		if (user != null && user.getEnable()) {
			return user;
		} else {
			return null;
		}
	}

	public User findEnabledUserByUsername(String username) {
		User user = userRepository.findUserByUsername(username);
		if (user != null && user.getEnable()) {
			return user;
		} else {
			return null;
		}
	}

	@Transactional
	public User validateUser(String confirmtoken) {
		UserManager userManager = getApplicationContext().getBean(UserManager.class);
		userManager.validateUser(confirmtoken);
		return userManager.getInstance();
	}

	public User createUser() {
		User user = new User();

		return user;
	}

	@Transactional
	public User registerUser(User user) {
		UserManager userManager = getApplicationContext().getBean(UserManager.class);
		userManager.setInstance(user);
		userManager.registerUser();

		// TODO 发email验证

		return userManager.getInstance();

	}

	@Transactional
	public User updateUserProfile(User user) {
		UserManager userManager = getApplicationContext().getBean(UserManager.class);
		userManager.saveUser(user);
		user = userManager.getInstance();

		return user;
	}

	@Transactional
	public void cancelUser(Long id) {

		UserManager userManager = getApplicationContext().getBean(UserManager.class);
		userManager.removeById(id);
	}

	public List<User> findTop10Users() {
		return userRepository.findTop10Users();
	}

	public UserFollowHotel findByUserIdAndHotelId(Long userId, Long hotelId) {
		return userFollowRepository.findByUserIdAndHotelId(userId, hotelId);
	}

}